package com.cal.utms.action.user_maintenance;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

import com.cal.utms.dao.user_maintenance.UserDaoImpl;
import com.cal.utms.dto.user_maintenance.ChangePasswordDto;
import com.cal.utms.entity.User;
import com.cal.utms.model.user_maintenance.UserModel;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ChangePasswordAction extends ActionSupport implements ModelDriven<ChangePasswordDto> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	UserDaoImpl daoImpl = new UserDaoImpl();
	private ChangePasswordDto changePasswordDto = new ChangePasswordDto();

	public String updatePassword() {
		String password = null;
		String newPassword = null;
		try {
			password = UserModel.encrypt(changePasswordDto.getOldPassword().trim());
			newPassword = UserModel.encrypt(changePasswordDto.getNewPassword().trim());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		User user = daoImpl.getUserByUsername(changePasswordDto.getUserName().trim());
		if (user != null) {
			if (user.getPassword().equals(password)) {
				daoImpl.changePassword(user, newPassword);
				changePasswordDto.setSuccess(true);
			} else {
				changePasswordDto.setResultMsg("2");
				changePasswordDto.setSuccess(false);
			}
		} else {
			changePasswordDto.setResultMsg("3");
			changePasswordDto.setSuccess(false);
		}
		return Action.SUCCESS;
	}

	@Override
	public ChangePasswordDto getModel() {
		return changePasswordDto;
	}

	public ChangePasswordDto getChangePasswordDto() {
		return changePasswordDto;
	}

	public void setChangePasswordDto(ChangePasswordDto changePasswordDto) {
		this.changePasswordDto = changePasswordDto;
	}

}
